package com.dchat.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dchat.domain.Member;
import com.dchat.domain.UserInfo;
import com.dchat.mapper.MemberMapper;
import com.dchat.service.inter.MemberService;
import com.dchat.util.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MemberServiceImp implements MemberService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private RedisOperator redisOperator;


    @Override
    @Async
    public void insertOne(Member member) {
        memberMapper.insert(member);
        ///更新缓存用户id
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id",member.getGroupId());
        List<Member> list = memberMapper.selectList(queryWrapper);

        List<Integer> ids = new ArrayList<>();
        for(Member member1:list){
            ids.add(member1.getMemberId());
        }
        redisOperator.cacheMemberId(member.getGroupId(),ids);
    }

    @Override
    public List<UserInfo> getMemberByGroupId(String id) {
        return memberMapper.getMemberByGroupId(id);
    }

    @Override
    public Member isMember(String groupId, Integer memberId) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id",groupId).eq("member_id",memberId);
        return memberMapper.selectOne(queryWrapper);
    }

    @Async
    @Override
    public void clearAll(String groupId) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id",groupId);
        memberMapper.delete(queryWrapper);
        redisOperator.clearMemberId(groupId);
    }

    @Async
    @Override
    public void deleteOne(String groupId, Integer memberId) {
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("group_id",groupId).eq("member_id",memberId);
        memberMapper.delete(queryWrapper);

        ///更新缓存用户id
        QueryWrapper<Member> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("group_id",groupId);
        List<Member> list = memberMapper.selectList(queryWrapper1);
        List<Integer> ids = new ArrayList<>();
        for(Member member:list){
            ids.add(member.getMemberId());
        }
        redisOperator.cacheMemberId(groupId,ids);
    }
}
